# -*- codeing=utf-8 -*-
# @Time : 2021/1/14 12:00
# @Author : 李思行
# @File : spider.py
# @Software : PyCharm

from bs4 import BeautifulSoup                        #网页解析，获取数据
import re                                            #正则表达式，进行文字匹配
import urllib.request,urllib.error                   #制定URL，获取网页数据
import xlwt                                          #进行excel操作
import sqlite3                                       #进行SQLite数据库操作

findLink=re.compile(r'<a href="(.*?)">')                                                #连接
findImage=re.compile(r'<img.*src="(.*?)" width="100"/>',re.S)                           #图片
findTitle=re.compile(r'<span class="title">(.*)</span>')                                #名字
findRating=re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')     #评分
findJudge=re.compile(r'<span>(\d*)人评价</span>')                                        #评价人数
findInq=re.compile(r'<span class="inq">(.*)</span>')                                    #概括
findBd=re.compile(r'<p class="">(.*?)</p>',re.S)                                        #演员表
def main():
    baseurl="https://movie.douban.com/top250?start="
    #1.爬取网页
    datalist=getData(baseurl)
    savepath=".\\豆瓣电影TOP250.xls"
    #3.保存数据
    saveData(datalist)

#爬取网站
def getData(baseurl):
    datalist=[]
    for i in range(0,10):
        url=baseurl+str(i*25)
        html=askURL(url)

    # 2.解析数据
        soup=BeautifulSoup(html,"html.parser")
        for item in soup.find_all('div',class_="item"):
        #for item in soup.select(".item"):
            data=[]
            item=str(item)
            link=re.findall(findLink,item)[0]
            data.append(link)
            imgSrc=re.findall(findImage,item)[0]
            data.append(imgSrc)
            titles=re.findall(findTitle,item)
            if(len(titles)==2):
                ctitle=titles[0]
                data.append(ctitle)
                otitle=' '.join(titles[1].replace('/','').split())
                data.append(otitle)
            else:
                data.append(titles[0])
                data.append(" ")
            rating=re.findall(findRating,item)[0]
            data.append(rating)
            judgeNum=re.findall(findJudge,item)[0]
            data.append(judgeNum)
            inq=re.findall(findInq,item)
            if  len(inq)!=0:
                inq=inq[0].replace("。","")
                data.append(inq)
            else:
                data.append(" ")

            bd=re.findall(findBd,item)[0]
            bd=re.sub('<br(\s+)?/>(\s+?)','',bd)
            bd=' '.join(bd.replace('/','').split())
            data.append(bd.strip())
            datalist.append(data)
    return datalist

#得到指定一个URL的网页内容
def askURL(url):
    header={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"}
    request=urllib.request.Request(url,headers=header)
    html=""
    try:
        response=urllib.request.urlopen(request)
        html=response.read().decode("utf-8")
        print(html)
    except Exception as e:
        if hasattr(e,"code"):
            print(e.code)
        if  hasattr(e,"reason"):
            print(e.reason)

    return html

#保存数据
def saveData(datalist):
    workbook=xlwt.Workbook(encoding="utf-8")
    worksheet=workbook.add_sheet('豆瓣电影TOP250.xls ')
    col=("电影详情链接","图片链接","影片中文名","影片外文名","评分","评价数","概况","相关信息")
    for i in range(0,8):
        worksheet.write(0,i,col[i])
    for i in range(0,250):
        print("第%d条"%i)
        data=datalist[i]
        for j   in  range(0,8):
            worksheet.write(i+1,j,data[j])
    workbook.save('豆瓣电影TOP250.xls')

if __name__ ==  "__main__":
    main()